package com.ck.util;

import com.ck.constant.ProfileConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * html工具类
 *
 * @author linqiang
 * @date 2018-08-13 16:57
 */
public class HtmlUtils {

    private static String STATIC_RESOURCE_CONTEXT = "http://47.106.15.189:9002";
    private static String STATIC_RESOURCE_CONTEXT_ = ".";
    private static String TEMPLATE_JSON_SYMBOL = "'###program###'";

    /**
     * 根据三屏html模板创建新的html
     *
     * @param templatePath    模板路径
     * @param newHtmlFilePath 新html路径
     * @param programJson     节目内容
     * @param activeProfile   当前环境(prod：生产环境， test或test01测试环境, dev开发环境)
     * @return 创建成功返回true, 反之false
     */
    public static File createNewHtmlByTemplateForThreeScreen(String templatePath, String newHtmlFilePath,
                                                             String programJson, String activeProfile) {
        StringBuilder str = new StringBuilder();
        try {
            String tempStr = "";
            //读取模块文件
            FileInputStream is = new FileInputStream(templatePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((tempStr = br.readLine()) != null) {
                str.append(tempStr).append("\r\n");
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        File f = null;
        try {
            String htmlContent = str.toString();
            if (StringUtils.isBlank(activeProfile)) {
                activeProfile = ProfileConstant.TEST01;
            }
            System.out.println("current profile : " + activeProfile);
            //生产环境将静态资源地址中‘http://47.106.15.189:9002’替换成‘.’
            if (ProfileConstant.PROD.equals(activeProfile)) {
                htmlContent = htmlContent.replace(STATIC_RESOURCE_CONTEXT, STATIC_RESOURCE_CONTEXT_);
            }
            //替换json数据
            String content = htmlContent.replace(TEMPLATE_JSON_SYMBOL, programJson);
            f = new File(newHtmlFilePath);
            BufferedWriter o = new BufferedWriter(new FileWriter(f));
            o.write(content);
            o.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("根据三屏html模板创建新的html失败：" + e.getMessage());
            return null;
        }
        return f;
    }
}
